package com.angcyo.uiview.github.luban;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;

import com.angcyo.github.utilcode.utils.FileUtils;
import com.angcyo.library.okhttp.Ok;
import com.angcyo.library.utils.L;
import com.angcyo.uiview.utils.RUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

import static com.angcyo.uiview.github.luban.Preconditions.checkNotNull;

/**
 * https://github.com/Curzibn/Luban
 */
public class Luban {

    public static final int THIRD_GEAR = 3;
    private static final int FIRST_GEAR = 1;
    private static final String TAG = "angcyo";
    private static String DEFAULT_DISK_CACHE_DIR = "luban_disk_cache";

    private static int sQuality = 90;

    private static volatile Luban INSTANCE;

    private final File mCacheDir;

    private OnCompressListener compressListener;
    private File mFile;
    private int gear = THIRD_GEAR;
    private String filename;

    private Luban(File cacheDir) {
        mCacheDir = cacheDir;
    }

    /**
     * Returns a directory with a default name in the private cache directory of the application to use to store
     * retrieved media and thumbnails.
     *
     * @param context A context.
     * @see #getPhotoCacheDir(Context, String)
     */
    private static synchronized File getPhotoCacheDir(Context context) {
        return getPhotoCacheDir(context, Luban.DEFAULT_DISK_CACHE_DIR);
    }

    /**
     * Returns a directory with the given name in the private cache directory of the application to use to store
     * retrieved media and thumbnails.
     *
     * @param context   A context.
     * @param cacheName The name of the subdirectory in which to store the cache.
     * @see #getPhotoCacheDir(Context)
     */
    private static File getPhotoCacheDir(Context context, String cacheName) {
        File cacheDir = context.getCacheDir();
        if (cacheDir != null) {
            File result = new File(cacheDir, cacheName);
            if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) {
                // File wasn't able to create a directory, or the result exists but not a directory
                return null;
            }

            File noMedia = new File(cacheDir + "/.nomedia");
            if (!noMedia.mkdirs() && (!noMedia.exists() || !noMedia.isDirectory())) {
                return null;
            }

            return result;
        }
        if (Log.isLoggable(TAG, Log.ERROR)) {
            Log.e(TAG, "default disk cache dir is null");
        }
        return null;
    }

    public static Luban get(Context context) {
        if (INSTANCE == null) INSTANCE = new Luban(Luban.getPhotoCacheDir(context));
        return INSTANCE;
    }

    /**
     * 旋转图片
     * rotate the image with specified angle
     *
     * @param angle  the angle will be rotating 旋转的角度
     * @param bitmap target image               目标图片
     */
    private static Bitmap rotatingImage(int angle, Bitmap bitmap) {
        //rotate image
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);

        //create a new image
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static Observable<ArrayList<String>> luban(Context context, String filePath) {
        if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
            return Observable.empty();
        }
        ArrayList<String> files = new ArrayList<>();
        files.add(filePath);
        return luban(context, files);
    }

    /**
     * 压缩一个列表的图片, 返回压缩后的图片路径列表
     */
    public static Observable<ArrayList<String>> luban(final Context context, ArrayList<String> originFilePathList) {
        if (originFilePathList == null || originFilePathList.isEmpty()) {
            return Observable.empty();
        }
        return Observable.from(originFilePathList)
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        if (s.startsWith("http")) {
                            return s;
                        }
                        return Luban.get(context.getApplicationContext()).thirdCompress(new File(s)).getAbsolutePath();
                    }
                })
                .scan(new Func2<String, String, String>() {
                    @Override
                    public String call(String s, String s2) {
                        return s + "|" + s2;
                    }
                })
                .last()
                .map(new Func1<String, ArrayList<String>>() {
                    @Override
                    public ArrayList<String> call(String s) {
                        ArrayList<String> list = new ArrayList<>();
                        String[] split = s.split("\\|");
                        for (int i = 0; i < split.length; i++) {
                            list.add(split[i]);
                        }
                        return list;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 返回原始路径和对应的缩略图路径
     */
    public static Observable<ArrayList<ImageItem>> luban2(final Context context, ArrayList<String> originFilePathList) {
        if (originFilePathList == null || originFilePathList.isEmpty()) {
            return Observable.empty();
        }
        return Observable.from(originFilePathList)
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        ImageItem imageItem = new ImageItem();
                        imageItem.path = s;
                        imageItem.thumbPath = Luban.get(context.getApplicationContext()).thirdCompress(new File(s)).getAbsolutePath();
                        return imageItem.toString();
                    }
                })
                .scan(new Func2<String, String, String>() {
                    @Override
                    public String call(String s, String s2) {
                        return s + ":" + s2;
                    }
                })
                .last()
                .map(new Func1<String, ArrayList<ImageItem>>() {
                    @Override
                    public ArrayList<ImageItem> call(String s) {
                        ArrayList<ImageItem> list = new ArrayList<>();
                        String[] split = s.split(":");
                        for (int i = 0; i < split.length; i++) {
                            list.add(ImageItem.get(split[i]));
                        }
                        return list;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    /**
     * 保存图片到系统相册目录
     *
     * @param bmp        位图对象
     * @param fileFolder 图片目录
     * @param filename   图片名称
     * @return 保存地址
     */
    public static String saveImageToSystemAlbum(Context context, Bitmap bmp, String fileFolder, String filename) {
        OutputStream stream = null;
        try {
            File saveDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), fileFolder);
            if (!saveDirectory.exists()) saveDirectory.mkdirs();
            File saveFile = new File(saveDirectory, filename);
            if (!saveFile.exists()) saveFile.createNewFile();
            stream = new BufferedOutputStream(new FileOutputStream(saveFile.getAbsolutePath()));
            Bitmap.CompressFormat format = Bitmap.CompressFormat.PNG;
            int quality = 100;
            bmp.compress(format, quality, stream);

            // 发送系统广播更新相册
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(saveFile);
            intent.setData(uri);
            context.sendBroadcast(intent);
            return saveFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String saveImageToSystemAlbum(Context context, File file, String fileFolder, String filename) {
        OutputStream stream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            File saveDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), fileFolder);
            if (!saveDirectory.exists()) saveDirectory.mkdirs();
            File saveFile = new File(saveDirectory, filename);
            if (!saveFile.exists()) saveFile.createNewFile();

            bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            stream = new BufferedOutputStream(new FileOutputStream(saveFile.getAbsolutePath()));

            byte[] read = new byte[1024];
            while (bufferedInputStream.read(read) != -1) {
                stream.write(read);
            }
            stream.flush();

            // 发送系统广播更新相册
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(saveFile);
            intent.setData(uri);
            context.sendBroadcast(intent);
            return saveFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 打印文件大小
     */
    public static void logFileSize(Context context, ArrayList<String> files) {
        for (String s : files) {
            File file = new File(s);
            if (file.exists()) {
                L.e(file.getAbsolutePath() + " " + getFileSize(context, file.length()));
            }
        }
    }

    public static String getFileSize(Context context, long size) {
        return Formatter.formatFileSize(context, size);
    }

    public static void logFileItems(Context context, ArrayList<ImageItem> files) {
        if (files == null) {
            return;
        }
        for (ImageItem s : files) {
            File originFile = new File(s.path);
            File thumbFile = new File(s.thumbPath);
            StringBuilder stringBuilder = new StringBuilder("\n");
            if (originFile.exists()) {
                stringBuilder.append("原始:");
                stringBuilder.append(originFile.getAbsolutePath());
                stringBuilder.append(" ");
                stringBuilder.append(Formatter.formatFileSize(context, originFile.length()));
                stringBuilder.append("\n");
            }
            if (thumbFile.exists()) {
                stringBuilder.append("压缩:");
                stringBuilder.append(thumbFile.getAbsolutePath());
                stringBuilder.append(" ");
                stringBuilder.append(Formatter.formatFileSize(context, thumbFile.length()));
                stringBuilder.append("\n");
            }
            L.e(stringBuilder.toString());
        }
    }

    /**
     * obtain the image's width and height
     *
     * @param imagePath the path of image
     */
    public static int[] getImageSize(String imagePath) {
        int[] res = new int[2];

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = 1;
        BitmapFactory.decodeFile(imagePath, options);

        res[0] = options.outWidth;
        res[1] = options.outHeight;

        return res;
    }

    public Luban launch() {
        checkNotNull(mFile, "the image file cannot be null, please call .load() before this method!");

        if (compressListener != null) compressListener.onStart();

        if (gear == Luban.FIRST_GEAR)
            Observable.just(mFile)
                    .map(new Func1<File, File>() {
                        @Override
                        public File call(File file) {
                            return firstCompress(file);
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnError(new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            if (compressListener != null) compressListener.onError(throwable);
                        }
                    })
                    .onErrorResumeNext(Observable.<File>empty())
                    .filter(new Func1<File, Boolean>() {
                        @Override
                        public Boolean call(File file) {
                            return file != null;
                        }
                    })
                    .subscribe(new Action1<File>() {
                        @Override
                        public void call(File file) {
                            if (compressListener != null) compressListener.onSuccess(file);
                        }
                    });
        else if (gear == Luban.THIRD_GEAR)
            Observable.just(mFile)
                    .map(new Func1<File, File>() {
                        @Override
                        public File call(File file) {
                            return thirdCompress(file);
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnError(new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            if (compressListener != null) compressListener.onError(throwable);
                        }
                    })
                    .onErrorResumeNext(Observable.<File>empty())
                    .filter(new Func1<File, Boolean>() {
                        @Override
                        public Boolean call(File file) {
                            return file != null;
                        }
                    })
                    .subscribe(new Action1<File>() {
                        @Override
                        public void call(File file) {
                            if (compressListener != null) compressListener.onSuccess(file);
                        }
                    });

        return this;
    }

    public Luban load(File file) {
        mFile = file;
        return this;
    }

    public Luban setCompressListener(OnCompressListener listener) {
        compressListener = listener;
        return this;
    }

    public Luban putGear(int gear) {
        this.gear = gear;
        return this;
    }

    /**
     * @deprecated
     */
    public Luban setFilename(String filename) {
        this.filename = filename;
        return this;
    }

    public Observable<File> asObservable() {
        if (gear == FIRST_GEAR)
            return Observable.just(mFile).map(new Func1<File, File>() {
                @Override
                public File call(File file) {
                    return firstCompress(file);
                }
            });
        else if (gear == THIRD_GEAR)
            return Observable.just(mFile).map(new Func1<File, File>() {
                @Override
                public File call(File file) {
                    return thirdCompress(file);
                }
            });
        else return Observable.empty();
    }

    private File thirdCompress(@NonNull File file) {
        String thumb = mCacheDir.getAbsolutePath() + File.separator +
                (TextUtils.isEmpty(filename) ? UUID.randomUUID().toString()/*System.currentTimeMillis()*/ : filename) +
                "." + FileUtils.getExtensionName(file.getName(), "jpg");

        double size;
        String filePath = file.getAbsolutePath();

        int angle = getImageSpinAngle(filePath);
        int[] imageSize = getImageSize(filePath);
        int width = imageSize[0];
        int height = imageSize[1];
        int thumbW = width % 2 == 1 ? width + 1 : width;
        int thumbH = height % 2 == 1 ? height + 1 : height;

        width = thumbW > thumbH ? thumbH : thumbW;
        height = thumbW > thumbH ? thumbW : thumbH;

        double scale = ((double) width / height);

        long fileLength = file.length();
        if (RUtils.getImageType(file) == Ok.ImageType.GIF //GIF 不压缩
                || fileLength <= 1024 * 300 /*300 kb 以下不压缩*/) {
            //GIF 图片, 不压缩直接重命名保存
            return copyTo(file, thumb, imageSize[0], imageSize[1]);
        }

        if (scale <= 1 && scale > 0.5625) {
            if (height < 1664) {
                if (fileLength / 1024 < 150)
                    return copyTo(file, thumb, thumbW, thumbH);//原本就已经很小的图片, 重命名保存
                size = (width * height) / Math.pow(1664, 2) * 150;
                size = size < 60 ? 60 : size;
            } else if (height >= 1664 && height < 4990) {
                thumbW = width / 2;
                thumbH = height / 2;
                size = (thumbW * thumbH) / Math.pow(2495, 2) * 300;
                size = size < 60 ? 60 : size;
            } else if (height >= 4990 && height < 10240) {
                thumbW = width / 4;
                thumbH = height / 4;
                size = (thumbW * thumbH) / Math.pow(2560, 2) * 300;
                size = size < 100 ? 100 : size;
            } else {
                int multiple = height / 1280 == 0 ? 1 : height / 1280;
                thumbW = width / multiple;
                thumbH = height / multiple;
                size = (thumbW * thumbH) / Math.pow(2560, 2) * 300;
                size = size < 100 ? 100 : size;
            }
        } else if (scale <= 0.5625 && scale > 0.5) {
            if (height < 1280 && fileLength / 1024 < 200)
                return copyTo(file, thumb, thumbW, thumbH);//原本就已经很小的图片, 重命名保存
            int multiple = height / 1280 == 0 ? 1 : height / 1280;
            thumbW = width / multiple;
            thumbH = height / multiple;
            size = (thumbW * thumbH) / (1440.0 * 2560.0) * 400;
            size = size < 100 ? 100 : size;
        } else {
            int multiple = (int) Math.ceil(height / (1280.0 / scale));
            thumbW = width / multiple;
            thumbH = height / multiple;
            size = ((thumbW * thumbH) / (1280.0 * (1280 / scale))) * 500;
            size = size < 100 ? 100 : size;
        }

        return compress(filePath, thumb, thumbW, thumbH, angle, (long) size);
    }

    private File firstCompress(@NonNull File file) {
        int minSize = 60;
        int longSide = 720;
        int shortSide = 1280;

        String filePath = file.getAbsolutePath();
        String thumbFilePath = mCacheDir.getAbsolutePath() + File.separator +
                (TextUtils.isEmpty(filename) ? System.currentTimeMillis() : filename) + ".jpg";

        long size = 0;
        long maxSize = file.length() / 5;

        int angle = getImageSpinAngle(filePath);
        int[] imgSize = getImageSize(filePath);
        int width = 0, height = 0;
        if (imgSize[0] <= imgSize[1]) {
            double scale = (double) imgSize[0] / (double) imgSize[1];
            if (scale <= 1.0 && scale > 0.5625) {
                width = imgSize[0] > shortSide ? shortSide : imgSize[0];
                height = width * imgSize[1] / imgSize[0];
                size = minSize;
            } else if (scale <= 0.5625) {
                height = imgSize[1] > longSide ? longSide : imgSize[1];
                width = height * imgSize[0] / imgSize[1];
                size = maxSize;
            }
        } else {
            double scale = (double) imgSize[1] / (double) imgSize[0];
            if (scale <= 1.0 && scale > 0.5625) {
                height = imgSize[1] > shortSide ? shortSide : imgSize[1];
                width = height * imgSize[0] / imgSize[1];
                size = minSize;
            } else if (scale <= 0.5625) {
                width = imgSize[0] > longSide ? longSide : imgSize[0];
                height = width * imgSize[1] / imgSize[0];
                size = maxSize;
            }
        }

        return compress(filePath, thumbFilePath, width, height, angle, size);
    }

    /**
     * obtain the thumbnail that specify the size
     *
     * @param imagePath the target image path
     * @param width     the width of thumbnail
     * @param height    the height of thumbnail
     * @return {@link Bitmap}
     */
    private Bitmap compress(String imagePath, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);

        int outH = options.outHeight;
        int outW = options.outWidth;
        int inSampleSize = 1;

        if (outH > height || outW > width) {
            int halfH = outH / 2;
            int halfW = outW / 2;

            while ((halfH / inSampleSize) > height && (halfW / inSampleSize) > width) {
                inSampleSize *= 2;
            }
        }

        options.inSampleSize = inSampleSize;

        int heightRatio = (int) Math.ceil(options.outHeight / (float) height);//
        int widthRatio = (int) Math.ceil(options.outWidth / (float) width);//

        if (heightRatio > 1 || widthRatio > 1) {
            if (heightRatio > widthRatio) {
                options.inSampleSize = heightRatio;
            } else {
                options.inSampleSize = widthRatio;
            }
        }
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(imagePath, options);
    }

    /**
     * obtain the image rotation angle
     *
     * @param path path of target image
     */
    private int getImageSpinAngle(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 指定参数压缩图片
     * create the thumbnail with the true rotate angle
     *
     * @param largeImagePath the big image path
     * @param thumbFilePath  the thumbnail path
     * @param width          width of thumbnail
     * @param height         height of thumbnail
     * @param angle          rotation angle of thumbnail
     * @param size           the file size of image
     */
    private File compress(String largeImagePath, String thumbFilePath, int width, int height, int angle, long size) {
        Bitmap thbBitmap = compress(largeImagePath, width, height);
        thbBitmap = rotatingImage(angle, thbBitmap);
        return saveImage(thumbFilePath, thbBitmap, size, thbBitmap.getWidth(), thbBitmap.getHeight());
    }

    /**
     * 保存图片到指定路径
     * Save image with specified size
     *
     * @param filePath the image file save path 储存路径
     * @param bitmap   the image what be save   目标图片
     * @param size     the file size of image   期望大小
     * @param width    width of thumbnail
     * @param height   height of thumbnail
     */
    private File saveImage(String filePath, Bitmap bitmap, long size, int width, int height) {
        checkNotNull(bitmap, TAG + "bitmap cannot be null");

        File result = new File(filePath.substring(0, filePath.lastIndexOf("/")));

        if (!result.exists() && !result.mkdirs()) return null;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        int options = sQuality;
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);

        while (stream.toByteArray().length / 1024 > size && options > 6) {
            stream.reset();
            options -= 6;
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, stream);
        }
        bitmap.recycle();
        try {
            filePath += "_s_" + width + "x" + height + ".jpg";
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(stream.toByteArray());
            fos.flush();
            fos.close();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new File(filePath);
    }

    private File copyTo(File file, String toPath, int width, int height) {
        String filePath = toPath;
        File targetFile = file;
        try {

            String exName = FileUtils.getExtensionName(file.getName(), "jpg");
            filePath = filePath.replaceAll("." + exName, "");//去除扩展名
            filePath += "_s_" + width + "x" + height + "." + exName;

            FileInputStream input = new FileInputStream(file);
            BufferedInputStream inBuff = new BufferedInputStream(input);

            // 新建文件输出流并对它进行缓冲
            targetFile = new File(filePath);
            FileOutputStream output = new FileOutputStream(targetFile);
            BufferedOutputStream outBuff = new BufferedOutputStream(output);

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();

            //关闭流
            inBuff.close();
            outBuff.close();

            output.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return targetFile;
    }

    /**
     * 2016-12-17
     */
    public Observable<File> start() {
        return putGear(THIRD_GEAR)
                .asObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

//    public static void save() {
//        new Thread() {
//            @Override
//            public void run() {
//                String zhenNN = "";
//                if (file.exists()) {
//                    zhenNN = BmpUtil.saveImageToSystemAlbum(HnPhotoPagerActivity.this, file,
//                            "ZhenNN", UUID.randomUUID().toString() + ".png");
//                } else {
//                    try {
//                        Bitmap bitmap = Glide.with(HnPhotoPagerActivity.this.getApplicationContext())
//                                .load(DraweeViewUtil.safeUrl(url))
//                                .asBitmap()
//                                .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
//                                .get();
//                        zhenNN = BmpUtil.saveImageToSystemAlbum(HnPhotoPagerActivity.this, bitmap,
//                                "ZhenNN", UUID.randomUUID().toString() + ".png");
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                final String s = zhenNN;
//                ThreadExecutor.instance().onMain(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (TextUtils.isEmpty(s)) {
//                            T.show(HnPhotoPagerActivity.this, "保存失败.");
//                        } else {
//                            T.show(HnPhotoPagerActivity.this, "已保存至:" + s);
//                        }
//                    }
//                });
//            }
//        }.start();
//    }

    public static class ImageItem {
        public String path = "";//源文件的路径
        public String thumbPath = "";//压缩后的文件路径
        public String url = "";//网络地址

        public ImageItem() {
        }

        public ImageItem(String path, String thumbPath, String url) {
            this.path = path;
            this.thumbPath = thumbPath;
            this.url = url;
        }

        public ImageItem(String path, String thumbPath) {
            this.path = path;
            this.thumbPath = thumbPath;
        }

        public ImageItem(String url) {
            this.url = url;
        }

        public static ArrayList<String> getImages(List<ImageItem> images) {
            ArrayList<String> list = new ArrayList<>();
            for (ImageItem item : images) {
                list.add(item.path);
            }
            return list;
        }

        public static ArrayList<String> getThumbImages(List<ImageItem> images) {
            ArrayList<String> list = new ArrayList<>();
            for (ImageItem item : images) {
                list.add(item.thumbPath);
            }
            return list;
        }

        public static ImageItem get(String string /* path|thumbPath 格式*/) {
            ImageItem imageItem = new ImageItem();
            if (TextUtils.isEmpty(string)) {
                return imageItem;
            }
            String[] split = string.split("\\|");
            if (split.length != 2) {
                imageItem.path = string;
                return imageItem;
            }
            imageItem.path = split[0];
            imageItem.thumbPath = split[1];
            return imageItem;
        }

        @Override
        public String toString() {
            return path + "|" + thumbPath;
        }

        @Override
        public boolean equals(Object obj) {
            if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(((ImageItem) obj).url)) {
                return TextUtils.equals(url, ((ImageItem) obj).url);
            }
            return TextUtils.equals(path, ((ImageItem) obj).path)
                    && TextUtils.equals(thumbPath, ((ImageItem) obj).thumbPath);
        }
    }
}